package com.yzy.fly.controller;

import com.alibaba.fastjson.JSONObject;
import com.yzy.fly.api.annotation.ApiDoc;
import com.yzy.fly.api.annotation.ApiOperation;
import com.yzy.fly.domain.RestMessage;
import com.yzy.fly.exception.UtilException;
import com.yzy.fly.kernel.controller.FlyConstant;
import com.yzy.fly.kernel.controller.FlyNoneController;
import com.yzy.fly.util.JsonUtil;
import com.yzy.fly.util.SqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@ApiDoc(desc = "常用工具")
@Slf4j
@RestController
@RequestMapping("/api/util")
public class UtilController extends FlyNoneController {

    @ApiOperation(value = "JSON格式化",notes = "JSON格式化输出",author="yinzhiyuan")
    @PostMapping(value = "/jsonFormat", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public RestMessage jsonFormat(@RequestBody String json){
        long statTime = System.currentTimeMillis();
        String formatJson = null;
        if (JsonUtil.isJSON(json)) {
            formatJson = JsonUtil.prettyFormat(json);
        }
        long endTime = System.currentTimeMillis();
        return RestMessage.success("执行成功",formatJson,(endTime-statTime));
    }

    @ApiOperation(value = "JSON合法性",notes = "判断内容是否为JSON的正确格式",author="yinzhiyuan")
    @PostMapping(value = "/isJson", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public RestMessage isJson(@RequestBody String json){
        long statTime = System.currentTimeMillis();
        boolean flag = JsonUtil.isJSON(json);
        long endTime = System.currentTimeMillis();
        return RestMessage.success("执行成功",flag,(endTime-statTime));
    }

    @ApiOperation(value = "SQL格式化",notes = "SQL格式化输出",author="yinzhiyuan")
    @PostMapping(value = "/sqlFormat", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public RestMessage sqlFormat(@RequestBody JSONObject params){
        long statTime = System.currentTimeMillis();
        String sql = params.getString("sql");
        String dbType = params.getString("dbType");
        try {
            sql = SqlUtil.sqlFormat(sql,dbType);
        } catch (UtilException e) {
            return RestMessage.fail(e.getMessage(),sql,0);
        }
        long endTime = System.currentTimeMillis();
        return RestMessage.success("执行成功",sql,(endTime-statTime));
    }

    @Override
    public String getType() {
        return FlyConstant.FLY_CORE;
    }
}
